import {Component, OnInit, Renderer2, AfterViewInit} from '@angular/core';
import {WebsocketService} from "@core/services/websocket/websocket.service";
import {Router} from "@angular/router";
import {Subscription} from "rxjs/internal/Subscription";
import * as CryptoJS from 'crypto-js';
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import {ApiService} from "@core/services/http/api.service";
import {AnalysisService} from "../analysis.service";

@Component({
  selector: 'control-index',
  templateUrl: './control-index.component.html',
  styleUrls: ['./control-index.component.scss']
})
export class ControlIndexComponent implements OnInit, AfterViewInit {
  messagesSubscription: Subscription;
  today = new Date();
  isVisible: boolean = false;                       // 为true时弹出登录对话窗
  wsId: string;                                     // WebsocketService 唯一标识
  times: any;                     // 初次打开页面时间戳(需保存至local)
  local = this.userAuthService.getUserInfoObj();
  num = Math.floor(Math.random() * 100 + 1);
  posts = [];                                       // 岗位列表
  isMenu: boolean = false;                          // 为true时弹出退出登录选项框
  loginTimes: any;
  saveLogin: any;
  year: any;
  title:string = '集群车宝指挥系统';
  companyLogo: any;                               // 5e746d2839bf6200014e3b20
  logoTitle: any;
  host:any = window.location.host;                // test57-6060.jekunauto.cn
  // host:any = 'test57-6060.jekunauto.cn';                // test57-6060.jekunauto.cn

  reportData = [
    {img: './assets/tmp/img/bi/control-index/swzk.png', title: '商务总控', href: '/analysis/totalControl', id: 'total'},
    {img: './assets/tmp/img/bi/control-index/mgzk.png', title: '门管总控', href: '/analysis/doorControl', id: 'door'},
    {img: './assets/tmp/img/bi/control-index/kfzk.png', title: '客服总控', href: '/analysis/customServiceControl', id: 'custom'},
    {img: './assets/tmp/img/bi/control-index/cgzk.png', title: '采购总控', href: '/analysis/purchaseControl', id: 'purchase'},
    {img: './assets/tmp/img/bi/control-index/clzk.png', title: '车辆总控', href: '/analysis/carControl', id: 'car'}
  ];
  postsBut = {name: '退出登录', id: 'esc'};

  constructor(private ws: WebsocketService,
              private router: Router,
              private msg: ApesMessageService,
              private renderer: Renderer2,
              private userAuthService: UserAuthService,
              private apiService: ApiService,
              private as: AnalysisService,) {
  }

  ngOnInit() {
    const date = new Date();
    this.year = date.getFullYear();
    this.as.getImges('如约车服1').then(value => {
      this.logoTitle = value;
      this.companyLogo = value ? 'https://'+this.host+'/fileserver/view/'+value : './assets/tmp/img/bi/3dTypeface.png';
    });
    // this.changeIsVisible();
    this.getWs();
  }

  changeIsVisible() {
    this.ws.close();

    this.times = new Date().getTime();
    this.wsId = CryptoJS.MD5(this.times + '' + typeof this.num).toString(CryptoJS.enc.Hex);
    this.ws.connect(this.wsId);

    if (!this.local) {
      this.isVisible = true;
      this.getWebSocket();
      setTimeout(() => this.initFocus(), 1000);

    } else {
      // 判断距离上一次登录是否相差15天 是否需要重新登录
      setTimeout(() => this.initFocus(), 1000);

      const userInfo = this.userAuthService.getUserInfoObj();
      this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
      this.posts = userInfo.userAccount.posts;
      this.posts.push(this.postsBut);
    }
  }

  ngAfterViewInit() {
  }

  /**
   * 定时器轮询，模拟websocket自动推送数据
   * 1、MD5识别码传入服务器缓存 aut.user.saveTvToken
   * 2、定时器每5秒询问一次接口查看接口返回数据是否已登录 aut.user.getTvToken
   * 3、返回数据已登录，销毁定时器，关闭二维码，并把登录数据存进storeUserInfoLocal
   * **/
  getWs() {
    this.times = new Date().getTime();
    this.wsId = CryptoJS.MD5(this.times + '' + typeof this.num).toString(CryptoJS.enc.Hex);

    // this.userModel['wsId'] = this.wsId;
    // 判断是否初次打开扫码登录
    if (!this.local) {
      this.isVisible = true;
      this.setMDstore(this.wsId);
      setTimeout(() => this.initFocus(), 1000);

    } else {
      const userInfo = this.userAuthService.getUserInfoObj() ;
      this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
      this.posts = userInfo.userAccount.posts;
      this.posts.push(this.postsBut);
      setTimeout(() => this.initFocus(), 1000);
    }
  }

  // md5信息存储
  setMDstore(key) {
    const data = { tokenId: key };
    this.apiService.post('aut.user.saveTvToken', { 'body': JSON.stringify(data) })
      .subscribe(body => {
        if (body) {
          this.saveLogin = body['login'];
          if (!this.saveLogin) {
            this.loginTimes = setInterval(() => {
              this.getLoginInfo(key);
            }, 5000);
          }
        }
      });
  }

  // 获取是否登录
  getLoginInfo(key) {
    const data = { tokenId: key };
    this.apiService.post('aut.user.getTvToken', { 'body': JSON.stringify(data) })
      .subscribe(body => {
        if (body) {
          this.saveLogin = body['login'];
          if (this.saveLogin) {
            clearInterval(this.loginTimes);
            this.isVisible = false;
            let userInfo = { 'token': body.user.sessionId, 'userAccount': body.user.user };
            this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
            this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
            // 登录成功 获取公司
            this.posts = userInfo.userAccount.posts;
            this.posts.push(this.postsBut);
            this.local = this.userAuthService.getUserInfoObj();
            this.msg.info('欢迎 ' + body.user.user.name + ' 登录成功');
          }
        }
      });
  }

  /** 调用 websocket **/
  getWebSocket() {
    this.messagesSubscription = this.ws.messagesObserver.subscribe( item => {
      const data = JSON.parse(item);
      if (data.topic === 'ws.loginTV') {
        this.isVisible = false;
        let userInfo = {'token': data.sessionId, 'userAccount': data.user};
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
        this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
        // 登录成功 获取公司
        this.posts = userInfo.userAccount.posts;
        this.posts.push(this.postsBut);
        this.msg.info('欢迎 ' + data.user.name + ' 登录成功');
        this.local = this.userAuthService.getUserInfoObj();
      }
    });
  }

  private $(id) {
    return document.getElementById(id);
  }

  // 获取焦点
  initFocus() {
    this.$('total').focus();
  }

  getFocus(id) {
  }

  getKey($event, index, click?: any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if (click === 1) {
      key = 0;
    } else if (click === 2) {
      key = 13;
    }
    let nextId;

    switch (key) {
      case 13:   // 确定键
        if (this.local) {
          this.router.navigateByUrl(this.reportData[index].href);
        } else {
          this.msg.error('请刷新后扫码登录');
        }
        break;
      case 37:   // 左
      case 38:   // 上
        if (index <= 0) {
          index = this.reportData.length - 1;
          nextId = this.reportData[index].id
        } else {
          nextId = this.reportData[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 39:   // 右
      case 40:   // 下
        if (index >= this.reportData.length - 1) {
          index = 0;
          nextId = this.reportData[index].id
        } else {
          nextId = this.reportData[index + 1].id;
        }
        this.$(nextId).focus();
        break;
      case 0:      // 搜索 | 设置
        if (this.local) {
          this.isMenu = true;
          // 如果弹出了退出对话框 将从对话框获取焦点
          setTimeout(() => {
            this.focusMenu(this.posts[0].id);
          }, 1000);
        } else {
          this.msg.error('请刷新后扫码登录');
        }
        break;
    }
  }


  /** 获取对话框焦点 ***/
  focusMenu(id) {
    this.$('total').blur();
    this.$(id).focus();
  }

  getMenus(key) {
  }

  changeMenu($event, postId: string, index, click?: any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if (click === 1) {
      key = 13;
    }
    let id = $event.target.id;
    let nextId;

    switch (key) {
      case 13:
        if (this.local) {
          if (id != 'esc') {
            this.changePost(postId);
          } else {
            this.userAuthService.removeUserInfo();
            this.router.navigateByUrl('');
            setTimeout(()=>{
              this.router.navigateByUrl('/analysis/control/index');
            },500)
          }
          this.isMenu = false;
        } else {
          this.msg.error('请刷新后扫码登录');
        }

        break;
      case 38:
        if (index <= 0) {
          index = this.posts.length - 1;
          nextId = this.posts[index].id
        } else {
          nextId = this.posts[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 40:
        if (index >= this.posts.length - 1) {
          index = 0;
          nextId = this.posts[index].id
        } else {
          nextId = this.posts[index + 1].id;
        }
        this.$(nextId).focus();
        break;
    }
  }

  changePost(postId: string) {
    // 检查数据的正确性
    let currentPost = this.posts.filter((post) => post.id == postId);
    if (currentPost.length === 0)
      return;
    // 检查是否改变 post
    let userInfo = this.userAuthService.getUserInfoObj();
    let currentPostInfo = userInfo.userAccount.post;
    if (postId === currentPostInfo.id)
      return;
    // 重新请求后端刷新菜单
    this.apiService.post('aut.user.bindPost', {'body': JSON.stringify({post: {id: postId}})}).subscribe(
      (body) => {
        userInfo.userAccount.post = currentPost[0];
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
        this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
        const postsData = userInfo.userAccount['localPermit'];
        //   .map(item => {
        //   const postId = userInfo.userAccount.post.company.id;
        //   if (postId === item.id) {
        //     return {name: item.name, id: item.id, checked: true}
        //   } else {
        //     return {name: item.name, id: item.id, checked: false}
        //   }
        // });
        const userCompany: any = this.as.unique(postsData);
        this.as.storeLocal(JSON.stringify(userCompany));
        window.location.reload();
      });
  }
}
